import { ref } from "vue";
import type { Component } from "vue";
import CommonModal from "@/components/CommonModal.vue";

export interface ModalOptions {
  type?: "info" | "success" | "warning" | "error" | "confirm";
  title?: string;
  message?: string;
  size?: "small" | "medium" | "large";
  showConfirmButton?: boolean;
  showCancelButton?: boolean;
  confirmButtonText?: string;
  cancelButtonText?: string;
  closable?: boolean;
  closeOnOverlayClick?: boolean;
  showFooter?: boolean;
  loading?: boolean;
  onConfirm?: () => void | Promise<void>;
  onCancel?: () => void;
  onClose?: () => void;
}

interface ModalInstance {
  id: string;
  component: Component;
  props: ModalOptions;
  resolve: (value: boolean) => void;
  reject: (reason?: unknown) => void;
}

class ModalManager {
  private modals = ref<ModalInstance[]>([]);
  private modalIdCounter = 0;

  // 创建模态框
  private createModal(options: ModalOptions): Promise<boolean> {
    return new Promise((resolve, reject) => {
      const id = `modal-${this.modalIdCounter++}`;

      const modalInstance: ModalInstance = {
        id,
        component: CommonModal,
        props: {
          ...options,
          onConfirm: async () => {
            try {
              if (options.onConfirm) {
                await options.onConfirm();
              }
              this.removeModal(id);
              resolve(true);
            } catch (error) {
              console.error("Modal confirm action failed:", error);
              // 不自动关闭，让用户决定
            }
          },
          onCancel: () => {
            if (options.onCancel) {
              options.onCancel();
            }
            this.removeModal(id);
            resolve(false);
          },
          onClose: () => {
            if (options.onClose) {
              options.onClose();
            }
            this.removeModal(id);
            resolve(false);
          },
        },
        resolve,
        reject,
      };

      this.modals.value.push(modalInstance);
    });
  }

  // 移除模态框
  private removeModal(id: string) {
    const index = this.modals.value.findIndex((modal) => modal.id === id);
    if (index !== -1) {
      this.modals.value.splice(index, 1);
    }
  }

  // 信息提示
  info(message: string, title = "提示"): Promise<boolean> {
    return this.createModal({
      type: "info",
      title,
      message,
      showCancelButton: false,
      confirmButtonText: "确定",
    });
  }

  // 成功提示
  success(message: string, title = "成功"): Promise<boolean> {
    return this.createModal({
      type: "success",
      title,
      message,
      showCancelButton: false,
      confirmButtonText: "确定",
    });
  }

  // 警告提示
  warning(message: string, title = "警告"): Promise<boolean> {
    return this.createModal({
      type: "warning",
      title,
      message,
      showCancelButton: false,
      confirmButtonText: "确定",
    });
  }

  // 错误提示
  error(message: string, title = "错误"): Promise<boolean> {
    return this.createModal({
      type: "error",
      title,
      message,
      showCancelButton: false,
      confirmButtonText: "确定",
    });
  }

  // 确认对话框
  confirm(
    message: string,
    title = "确认",
    options: Omit<ModalOptions, "type" | "title" | "message"> = {},
  ): Promise<boolean> {
    return this.createModal({
      type: "confirm",
      title,
      message,
      showCancelButton: true,
      confirmButtonText: "确认",
      cancelButtonText: "取消",
      ...options,
    });
  }

  // 自定义模态框
  custom(options: ModalOptions): Promise<boolean> {
    return this.createModal(options);
  }

  // 获取所有模态框
  getModals() {
    return this.modals;
  }

  // 关闭所有模态框
  closeAll() {
    this.modals.value.forEach((modal) => {
      if (modal.props.onClose) {
        modal.props.onClose();
      }
      modal.resolve(false);
    });
    this.modals.value = [];
  }
}

// 创建全局模态框管理器实例
export const modalManager = new ModalManager();

// 导出便捷方法
export const useModal = () => {
  return {
    info: (message: string, title?: string) =>
      modalManager.info(message, title),
    success: (message: string, title?: string) =>
      modalManager.success(message, title),
    warning: (message: string, title?: string) =>
      modalManager.warning(message, title),
    error: (message: string, title?: string) =>
      modalManager.error(message, title),
    confirm: (
      message: string,
      title?: string,
      options?: Omit<ModalOptions, "type" | "title" | "message">,
    ) => modalManager.confirm(message, title, options),
    custom: (options: ModalOptions) => modalManager.custom(options),
    closeAll: () => modalManager.closeAll(),
    modals: modalManager.getModals(),
  };
};

// 导出模态框容器组件
export const ModalContainer = defineComponent({
  name: "ModalContainer",
  setup() {
    const modals = modalManager.getModals();

    return () => {
      return modals.value.map((modal) => {
        return h(
          "div",
          {
            key: modal.id,
            class: "modal-container",
            style: {
              position: "fixed",
              top: "0",
              left: "0",
              right: "0",
              bottom: "0",
              pointerEvents: "none",
              zIndex: "9999",
            },
          },
          [
            h(modal.component, {
              ...modal.props,
              style: {
                pointerEvents: "auto",
              },
            }),
          ],
        );
      });
    };
  },
});

// 导入 Vue 的 h 函数和 defineComponent
import { h, defineComponent } from "vue";
